#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "cJSON.h"
#include "req_handle.h"
#include "log_console.h"
#include "custom_handle.h"
#include <shmem.h>
#include "Modbus.h"

#define KB 1024
#define HTML_SIZE (64 * KB)

//普通的文本回复需要增加html头部
#define HTML_HEAD "Content-Type: text/html\r\n" \
                  "Connection: close\r\n"
#define JSON_HEAD "Content-Type: application/json\r\n" \
                  "Connection: close\r\n"
/**
 * @brief 处理自定义请求，在这里添加进程通信
 * @param input
 * @return
 */
int parse_and_process(char *input)
{
    if (strncmp(input, "username", 8) == 0)
    {
        //登录判断
        //分割函数字符串
        char *token_name = NULL;
        char *token_pwd = NULL;
        token_name = strtok_r(input, "&", &token_pwd);
        char *name = NULL;
        strtok_r(token_name, "=", &name); //用户名
        char *pwd = NULL;
        strtok_r(token_pwd, "=", &pwd); //密码

        char reply_buf[HTML_SIZE] = {0};

        if (strcmp(name, "admin") == 0 && strcmp(pwd, "admin") == 0)
        {
            strcpy(reply_buf, "<script>window.location.href = '/temp_index.html';</script>");
            log_console("req = %s\n", reply_buf);
            fputs(reply_buf, stdout);
        }
        else
        {
            strcpy(reply_buf, "<script charset='UTF-8'>alert('name or password is wrong!');</script>");
            strcat(reply_buf, "<script>window.location.href = '/login.html';</script>");
            fputs(reply_buf, stdout);
        }
    }
    else
    {
        /* 解析网页发来的json格式请求，判断是哪个页面的请求 */
        cJSON *root = NULL;
        cJSON *item = NULL;
        root = cJSON_Parse(input);
        if (!root)
        {
            printf("Error before: [%s]\n", cJSON_GetErrorPtr());
        }
        else
        {
            item = cJSON_GetObjectItem(root, "type");
            if (item->valueint == 1)
            {
                char msg[1024];
                GetProcess_modbus(msg);
                report_json(msg);
            }
            else if (item->valueint == 2)
            {
                char msg[1024];
                GetProcess_stm32(msg);
                report_json(msg);
            }
            else if (item->valueint == 0)
            {
                char msg[1024];
                cJSON *root = cJSON_CreateObject();
                cJSON *array = cJSON_CreateArray();
                cJSON_AddItemToObject(root, "data", array);
                cJSON *node1 = cJSON_CreateObject();
                cJSON *node2 = cJSON_CreateObject();

                cJSON_AddItemToObject(node1, "key", cJSON_CreateNumber(1));
                cJSON_AddItemToObject(node1, "val", cJSON_CreateString("Linux"));
                cJSON_AddItemToArray(array, node1);

                cJSON_AddItemToObject(node2, "key", cJSON_CreateNumber(2));
                cJSON_AddItemToObject(node2, "val", cJSON_CreateString("Version 1.0"));
                cJSON_AddItemToArray(array, node2);
                strcpy(msg, cJSON_Print(root));
                report_json(msg);
            }
        }
    }
    return 0;
}

int report_json(const char *msg)
{
    char reply_buf[HTML_SIZE] = {0};
    sprintf(reply_buf, "%sContent-Length: %ld\r\n\r\n", JSON_HEAD, strlen(msg));
    strcat(reply_buf, msg);
    fputs(reply_buf, stdout);

    return 0;
}

//共享内存
void GetProcess_modbus(char *msg)
{
    shm_init(&para, "modbus_shm", 1024);
    struct modbus_data *modbus_addr = shm_getaddr(&para);
    if (modbus_addr == NULL)
    {
        return;
    }
    //创建一个json对象
    cJSON *json1 = cJSON_CreateObject();
    // cJSON_AddItemToObject(json1, "type", cJSON_CreateNumber(1));   //采集回复指令
    // cJSON_AddItemToObject(json1, "result", cJSON_CreateNumber(0)); //成功返回0，失败返回1
    cJSON *array1 = NULL;
    cJSON_AddItemToObject(json1, "data", array1 = cJSON_CreateArray());

    //向json存入modbus数据
    char val[32] = "";
    cJSON *data_json = cJSON_CreateObject();
    snprintf(val, 32, "%.2lf", modbus_addr->temperature);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(101));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(modbus_addr->temperature));
    cJSON_AddItemToArray(array1, data_json);

    data_json = cJSON_CreateObject();
    snprintf(val, 32, "%.2lf", modbus_addr->humidity);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(102));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(modbus_addr->humidity));
    cJSON_AddItemToArray(array1, data_json);

    data_json = cJSON_CreateObject();
    snprintf(val, 32, "%d", modbus_addr->air_switch);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(103));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(modbus_addr->air_switch));
    cJSON_AddItemToArray(array1, data_json);

    data_json = cJSON_CreateObject();
    snprintf(val, 32, "%.2lf", modbus_addr->air_temp);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(104));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(modbus_addr->air_temp));
    cJSON_AddItemToArray(array1, data_json);

    data_json = cJSON_CreateObject();
    snprintf(val, 32, "%d", modbus_addr->light);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(105));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(modbus_addr->light));
    cJSON_AddItemToArray(array1, data_json);

    strcpy(msg, cJSON_Print(json1));
}
void GetProcess_stm32(char *msg)
{
    shm_init(&para, "stm32_shm", 1024);
    struct stm32_data *stm32_addr = shm_getaddr(&para);
    if (stm32_addr == NULL)
    {
        return;
    }
    cJSON *json2 = cJSON_CreateObject();
    // cJSON_AddItemToObject(json2, "type", cJSON_CreateNumber(1));   //采集回复指令
    // cJSON_AddItemToObject(json2, "result", cJSON_CreateNumber(0)); //成功返回0，失败返回1
    cJSON *array2 = NULL;
    cJSON_AddItemToObject(json2, "data", array2 = cJSON_CreateArray());

    //向json存入stm32数据
    char val[32] = "";
    cJSON *data_json = cJSON_CreateObject();
    snprintf(val, 32, "%d", stm32_addr->led);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(301));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(stm32_addr->led));
    cJSON_AddItemToArray(array2, data_json);

    data_json = cJSON_CreateObject();
    snprintf(val, 32, "%d", stm32_addr->Light);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(303));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(stm32_addr->Light));
    cJSON_AddItemToArray(array2, data_json);

    data_json = cJSON_CreateObject();
    snprintf(val, 32, "%.2lf", stm32_addr->bat);
    cJSON_AddItemToObject(data_json, "key", cJSON_CreateNumber(302));
    cJSON_AddItemToObject(data_json, "val", cJSON_CreateNumber(stm32_addr->bat));
    cJSON_AddItemToArray(array2, data_json);

    strcpy(msg, cJSON_Print(json2));
}